#This script will amalgamate all datafiles based on point_ID or georef_ID
#Establish directories

in.dir="C:/R/In"
out.dir="C:/R/Out/"
setwd(in.dir)

#Read in .csv files

raw.sample = read.csv("Sample.csv", header=T)
raw.ASCII = read.csv("Master.csv", header=T)
raw.MODIS = read.csv("MODIS Transformed.csv", header=T)
raw.rocks = read.csv("Rocks.csv", header=T)
raw.logs = read.csv("Logs.csv", header=T)
raw.HEMI.road = read.csv("HEMI from road avg by georef.csv", header=T)
raw.HEMI.forest = read.csv("HEMI from forest avg by georef.csv", header=T)
raw.LL = read.csv("Leaf Litter Standing Crop Mean per Site.csv", header=T)

#Merge all objects to create one final Master Spreadsheet

compile.1 = data.frame(raw.sample, raw.ASCII)
compile.2= merge(compile.1, raw.MODIS, by=c("point_ID"), all.x=T)
compile.3 = merge(compile.2, raw.logs, by=c("georef_ID"), all.x=T)
compile.4 = merge(compile.3, raw.rocks, by=c("georef_ID"), all.x=T)
compile.5 = merge(compile.4, raw.HEMI.road, by=c("georef_ID"), all.x=T)
compile.6 = merge(compile.5, raw.HEMI.forest, by=c("georef_ID"), all.x=T)
compile.7 = merge(compile.6, raw.LL, by=c("georef_ID"), all.x=T)

#Write out the .csv Master File

write.csv(x=compile.7, file=paste(out.dir,"mastertoedit.csv",sep=""), row.names=F)

#File was manually edited to change some column names, now re-import and merge with abundance averaged by georef to make the last data set

raw.max = read.csv("max abund by site.csv", header=T)
raw.avg = read.csv("avg abund by site.csv", header=T)
master.sample = read.csv("samplesmaster.csv", header=T)

#Firest merge raw.max and raw.avg leaving all.x=F to dis-include georefs which had fewer than 2 surveys
#These sites were manually vetted from raw.avg

compile.8 = merge(raw.max, raw.avg, by=c("georef_ID"))
nrow(compile.8)
compile.9 = merge(compile.8, master.sample, by=c("georef_ID"))

t.mean = function(x){return(mean(x,na.rm=T))}
check = aggregate(compile.9, by=list(compile.9$georef_ID), FUN=t.mean)
compile.10 = merge(check, compile.9, by=c("georef_ID"),all.x=F)
str(compile.9)




#Write out the file as .csv

write.csv(x=check, file=paste(out.dir,"masterbygeoreftoedit.csv",sep=""), row.names=F)